from flask import Flask, request, jsonify
import requests
import json

app = Flask(__name__)

@app.route('/chat', methods=['POST'])
def chat():
    jsonForm = request.form

    url = "https://api.coze.cn/v3/chat"
    headers = {
        "Authorization": "Bearer pat_w9cYWPXWMz1ws0i62iwaNUuAYpNmq9CIj9HjWhVp1ZpZp70HHcTbgxYyFnnQsd5s",
        "Content-Type": "application/json"
    }
    data = {
        "bot_id": "7481923944573501480",
        "user_id": "123",
        "auto_save_history": True,
        "additional_messages": [
            {
                "content": jsonForm["content"],
                "content_type": "text",
                "role": "user"
            }
        ],
        "stream": True
    }

    try:
        # 启用流式请求
        with requests.post(url, headers=headers, json=data, stream=True) as response:
            if response.status_code == 200:
                contents = []
                # 逐块读取响应内容
                for chunk in response.iter_content(chunk_size=None):
                    chunk_str = chunk.decode('utf-8')
                    start_index = chunk_str.find('event:conversation.message.delta')
                    if start_index != -1:
                        next_event_index = chunk_str.find('event:', start_index + 1)
                        if next_event_index == -1:
                            end_index = len(chunk_str)
                        else:
                            end_index = next_event_index
                        event_module = chunk_str[start_index:end_index]

                        # 找到大括号的起始和结束位置
                        start_index = event_module.find('{')
                        end_index = event_module.rfind('}') + 1

                        if start_index != -1 and end_index != -1:
                            # 截取大括号中的内容
                            json_content = event_module[start_index:end_index]
                            data_dict = json.loads(json_content)
                            contents.append(data_dict["content"])
                return jsonify({"contents": contents})
            else:
                return jsonify({"error": f"请求失败，状态码：{response.status_code}", "message": response.text})
    except Exception as e:
        return jsonify({"error": str(e)})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=3000)